package com.xiaoming.e3mall.search.service.impl;

import com.xiaoming.e3mall.common.pojo.SearchResult;
import com.xiaoming.e3mall.search.dao.SearchDao;
import com.xiaoming.e3mall.search.service.SearchService;
import org.apache.solr.client.solrj.SolrQuery;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * 商品搜索Service
 */
@Service
public class SearchServiceImpl  implements SearchService{

    @Autowired
    private SearchDao searchDao;


    /**
     * Controller 调用 dubbo发布的服务 封装 SolrQuery对象
     */
    @Override
    public SearchResult search(String keyword, int page, int rows) throws Exception {
        //创建一个SolrQuery对象
        SolrQuery query = new SolrQuery();
        //设置默认搜索域
        query.set("df", "item_title");
        //设置查询的关键字
        query.setQuery(keyword);
        //设置分页条件
          //开始位置 当前页减1 * 每页记录数
        query.setStart((page-1)*rows);
        query.setRows(rows);
        //设置高亮显示
        query.setHighlight(true);
        //设置哪个域高亮
        query.addHighlightField("item_title");
        //设置高亮的前缀
        query.setHighlightSimplePre("<em style=\"color:red\">");
        query.setHighlightSimplePost("</em>");

        //执行查询
        SearchResult result = searchDao.search(query);
        //根据返回的result 计算 页数
        //总记录数
        long recordCount = result.getRecordCount();
        //计算总页数
        int pageCount = (int) ((recordCount+rows-1)/rows);
        result.setTotalPages(pageCount);
        return result;
    }
}
